import React, { Component } from 'react'
import Form from './Form'
import ListItems from './ListItems'
import "./todo.css"
import "./common.scss"
import Dialog from './Dialog'

export default class Todolist extends Component {

  constructor() {
    super();
    this.state = {
      keyword: '',
      showEdit: false,
      currentTodo: {},
      datalist: [{
        id: 1,
        name: "beijing"
      },
      {
        id: 2,
        name: "taiyuan"
      }
      ]
    }
  }

  handleAdd(name) {
    console.log(name)
    this.state.datalist.push({
      id: new Date().getTime(),
      name
    })
    this.setState({})
  }

  handleSearch(keyword) {
    this.setState({
      keyword
    })
  }

  handleDel(id) {
    console.log(id);
    this.state.datalist.find((item, index) => {
      if (item.id === id) {
        this.state.datalist.splice(index, 1)
        return true;
      }
    })
    this.setState({})
  }


  handleEdit(id) {
    console.log(id);
    let todo = this.state.datalist.find((item, index) => {
      if (item.id === id) {
        return true;
      }
    })

    this.setState({
      currentTodo: todo,
      showEdit: true
    })

  }

  handleSubmit = () => {
    let txt = this.refs.name.value;
    this.state.datalist.find((item, index) => {
      if (item.id === this.state.currentTodo.id) {
        this.state.datalist[index].name=txt;
        return true;
      }
    })
    this.setState({
      showEdit:false
    })
    
  }

  render() {

    let list = this.state.datalist.filter((item, index) => {
      return item.name.indexOf(this.state.keyword) > -1;
    })

    let edit = <Dialog title="编辑">
      <input type="text" ref="name" defaultValue={this.state.currentTodo.name} />
      <button onClick={this.handleSubmit}>提交</button>
      <button>取消</button>
    </Dialog>;

    return (
      <div>
        <Form add={(name) => this.handleAdd(name)}
          search={(name) => this.handleSearch(name)}
        ></Form>
        <ListItems list={list}
          del={(id) => this.handleDel(id)}
          edit={(id) => this.handleEdit(id)}

        ></ListItems>
        {
          this.state.showEdit ? edit : ''
        }

      </div>
    )
  }
}
